Scope of Variables
- All variables in a program may not be accessible at all locations in that program.
- This depends on where we have declared a variable.
- The scope of a variable determines the portion of the program where we can access a particular identifier.
There are two basic scopes of variables in Python −
- Global variables
- Local variables
Local Variables | Global Variables |
---|---|
Variables are defined inside a function body | Variables are defined outside of any function |
Local variables can be accessed only inside the function in which they are declared | Global variables can be accessed throughout the program body by all functions. |
Local variables exist within functions. | Global Variables exist outside of functions. |
Example 1: Printing global variable outside the function
glb_var = "global"def var_function():lcl_var = "local"print(lcl_var)var_function()print(glb_var)Outputlocalglobal
Example 2: Printing global variable inside and outside the function
glb_var = "global"def var_function():lcl_var = "local"print(lcl_var)print(glb_var)var_function()print(glb_var)Outputlocalglobalglobal
Let’s look at another example where we use the same variable name for a global variable and a local variable:
num1 = 5def my_function():num1 = 10num2 = 7print(num1)print(num2)my_function()print(num1)Output1075
Inside the function num1 has the value 10 since it is locally assigned and outside the function num1 has the value 5 since it has global value.
We can create a global variables within a function by using Python’s global statement as follows:
def new_shark(): global shark shark = "Sammy" new_shark() print(shark) Output: Sammy
export const _frontmatter = {"title":"Scope of Variables","metaTitle":"Python - Scope of Variables","metaDescription":"Python - Scope of Variables"}
References
- Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
- Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
- John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
- Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
- Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
- Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
- Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.